jQuery(document).ready(function () {

	// REQUEST HANDLERS //
	
	function onCategoriesReceived(data) {
		if (data.error == null) {
			addCategories(data.data);
		}
	};

	function onPostReceived(data) {
		console.log(JSON.stringify(data));
		if (data.error == null) {
			addTitle(data.data.title);
			addDate(data.data.date);
			addPost(data.data.content);
		}
	};

	// BLOG HANDLERS //

	function addCategories(categories) {
		for (var i = 0; i < categories.length; i++) {
			jQuery("<li></li>").appendTo("#categories ul").append(
				jQuery("<a></a>", {
					text: categories[i].value,
					href: "#"
			}));
		}
	};

	function addPost(content) {
		var paragrafs = content.split("\n\n");
		removePost();

		for (var i = 0; i < paragrafs.length; i++) {
			jQuery("<p></p>", {
				text: paragrafs[i]
			}).appendTo("#mainContent article div");
		}
	};

	function addTitle(title) {
		jQuery("#blogTitle").text(title);
	};

	function addDate(value) {
		var date = new Date(value);
		jQuery("#datetime").text(date.toDateString());
	}

	function removePost() {
		jQuery("#mainContent article div p").remove();
	};

	// UTIL METHODS //
	
	function getURLParameter(name) {
		var result = new RegExp("[\\?&]" + name + "=([^&#]*)").exec(window.location.href);
		return (result != null ? result[1] : null);
	};

	// MAIN //
	
	var categotyURL = "http://springleafweb.appspot.com/get-all-categories";
	var postURL = "http://springleafweb.appspot.com/get-blog-post";
	var post = getURLParameter("post");

	jQuery.get(categotyURL, onCategoriesReceived);
	jQuery.get((post != null ? postURL + "?post=" + post : postURL), onPostReceived);
});